import serial
import time
from rclpy.node import Node
class SerialPort(Node):
    def __init__(self, port, baudrate):
        super().__init__("serial_port")
        self.port = port
        self.baudrate = baudrate
        self.serial_conn = None

    def open(self):
        """打开串口连接"""
        try:
            self.serial_conn = serial.Serial(self.port, self.baudrate, timeout=0.1)
            print(f"串口已打开: {self.port}")
        except serial.SerialException as e:
            self.get_logger().warning(f"无法打开串口: {e}")
            self.get_logger().warning('-----------------sls------------------')
            self.get_logger().warning('检查端口号，检查波特率')            
            self.get_logger().warning("-----------------sls------------------")

    def close(self):
        """关闭串口连接"""
        if self.serial_conn and self.serial_conn.is_open:
            self.serial_conn.close()
            print("串口已关闭")

    def is_data_available(self):
        """检查是否有数据可读"""
        if self.serial_conn and self.serial_conn.is_open:
            return self.serial_conn.in_waiting > 0
        return False

    def read_data(self):
        """读取串口数据"""
        if self.is_data_available():
            strdata = self.serial_conn.read_all().decode('utf-8').strip()
            print(strdata)
            lines = strdata.splitlines()
            return int(lines[-1])
        else:
            return -1

def main():
    # 创建串口对象
    serial_port = SerialPort('/dev/ttyACM0', 115200)
    # 打开串口
    serial_port.open()
    while True:
        # 检查是否有数据可读
        print(serial_port.read_data())
        time.sleep(0.1)


        # else:
        #     print('nodata')
        #     time.sleep(1)

if __name__ == "__main__":
    main()